#include "MainWidget.h"
#include "ui_MainWidget.h"
#include <QDebug>
#include <QButtonGroup>
#include <QMessageBox>
#include <QJsonArray>
#include "dialogadd.h"
#include "qthelper.h"
#include <QItemSelectionModel>
#include "widgetlogin.h"


MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    if(m_modelData == NULL)
        m_modelData = new QStandardItemModel();

    if(m_AppJson == NULL)
        m_AppJson = new AppJson();

    this->initForm();
    this->initConfig();
}

MainWidget::~MainWidget()
{
    if(m_Comm)
    {
        unConnect();
    }

    SaveData();

    if(m_AppJson != NULL)
        delete m_AppJson;

    if(m_modelData != NULL)
        delete m_modelData;

    delete ui;
}

void MainWidget::setDialog(WidgetLogin *dlg1)
{
    dialogLogin = dlg1;
}


void MainWidget::initForm()
{
    this->setWindowTitle("开关机工具");
    // 获取当前窗口标志
    Qt::WindowFlags winflags = this->windowFlags();
    // 移除最大化按钮标志
    winflags &= ~Qt::WindowMaximizeButtonHint;
    // 应用新的窗口标志
    this->setWindowFlags(winflags);

    // 创建一个按钮组
    QButtonGroup *radioGroup = new QButtonGroup(this);

    // 将单选按钮添加到按钮组中
    radioGroup->addButton(ui->radioButtonTCP);
    radioGroup->addButton(ui->radioButtonUDP);
    // 可以为每个按钮设置一个唯一的ID，方便后续获取选中按钮的信息
    //radioGroup->setId(ui->radioButtonTCP, true);
    //radioGroup->setId(ui->radioButtonUDP, false);

    ui->pushButtonLink->setText("打开连接");
    ui->pushButtonLink->setStyleSheet("color: red;");


    QIntValidator *validator = new QIntValidator(1, 99999, ui->lineEditPort);
    ui->lineEditPort->setValidator(validator);

    QRegExp ipRegex("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    QRegExpValidator *validatorIP = new QRegExpValidator(ipRegex, ui->lineEditIP);
    ui->lineEditIP->setValidator(validatorIP);

    // 读取JSON数据
    m_jsonDoc = m_AppJson->readJsonFromFile();

    m_modelData->setHorizontalHeaderLabels({"id","事件名称", "开关机","墙ID","地址"});
    if (!m_jsonDoc.isNull() && m_jsonDoc.isObject()) {
        QJsonObject jsonObj = m_jsonDoc.object();

        QString qstrComm = jsonObj["comm"].toString();
        if(qstrComm == "TCP" || qstrComm.isEmpty())
            ui->radioButtonTCP->setChecked(true);
        else
            ui->radioButtonUDP->setChecked(true);

        QString qstrIP = jsonObj["ip"].toString();
        if(qstrIP.isEmpty())
            qstrIP = "127.0.0.1";
        ui->lineEditIP->setText(qstrIP);

        QString qstrPort = jsonObj["port"].toString();
        if(qstrPort.isEmpty())
            qstrPort = "6000";
        ui->lineEditPort->setText(qstrPort);

        //QString qstrWallid = jsonObj["wallid"].toString();
        //if(qstrWallid.isEmpty())
        //    qstrWallid = "0";
        //ui->lineEditWallId->setText(qstrWallid);

        // 读取数组
        if(jsonObj["data"].isArray())
        {
            QJsonArray jsonData = jsonObj["data"].toArray();
            if(jsonData.size()>0)
            {
                QJsonArray::iterator jsonite =  jsonData.begin();
                while(jsonite != jsonData.end())
                {
                    QJsonObject data = jsonite->toObject();
                    QList<QStandardItem*> items;
                    items << new QStandardItem(data["gid"].toString())
                          << new QStandardItem(data["gname"].toString())
                          << new QStandardItem(QVariant(data["gturn"].toString()).toBool()?"开机":"关机")
                          << new QStandardItem(data["gwallid"].toString())
                          << new QStandardItem(data["gadd"].toString());
                    m_modelData->appendRow(items);

                    jsonite++;
                }

            }
        }

    }
    ui->tableViewData->setModel(m_modelData);
    //选中单行
    ui->tableViewData->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableViewData->setSelectionBehavior(QAbstractItemView::SelectRows);
    // 禁用双击编辑功能
    ui->tableViewData->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableViewData->setAlternatingRowColors(true);//交替颜色
    ui->tableViewData->horizontalHeader()->setStretchLastSection(true);
    ui->tableViewData->setColumnWidth(1,160);
    ui->tableViewData->setColumnWidth(2,60);
    ui->tableViewData->setColumnWidth(3,60);
    ui->tableViewData->hideColumn(0);
    ui->tableViewData->show();
}

void MainWidget::initConfig()
{
    connect(ui->pushButtonRun, &QPushButton::clicked, this, &MainWidget::onButtonRunClicked);
    connect(ui->pushButtonNew, &QPushButton::clicked, this, &MainWidget::onButtomNewClicked);
    connect(ui->pushButtonUpdate, &QPushButton::clicked, this, &MainWidget::onButtomUpdateClicked);
    connect(ui->pushButtonDel, &QPushButton::clicked, this, &MainWidget::onButtomDelClicked);
    connect(ui->pushButtonLink, &QPushButton::clicked, this, &MainWidget::onButtomLinkClicked);
    connect(ui->pushButtonRtLogin, &QPushButton::clicked, this, &MainWidget::onButtonRtLoginClicked);

    m_TcpSocket = new QTcpSocket(this);
    connect(m_TcpSocket, &QTcpSocket::connected, this,&MainWidget::TcpConnected);
    connect(m_TcpSocket, &QTcpSocket::disconnected, this, &MainWidget::TcpDisconnected);
    connect(m_TcpSocket, &QTcpSocket::readyRead, this, &MainWidget::TcpReadyRead);
    connect(m_TcpSocket, &QTcpSocket::errorOccurred, this, &MainWidget::TcpDisplayError);

    m_UdpSocket = new QUdpSocket(this);
    connect(m_UdpSocket, &QUdpSocket::readyRead, this, &MainWidget::UdpReadyRead);



    // 绑定本地端口，用于接收数据
    //if (!m_UdpSocket->bind(QHostAddress::Any, 12345)) {
    //    qDebug() << "Failed to bind UDP socket";
    //}
}

void MainWidget::TcpConnected()
{
    qDebug() << "Connected to server";
}

void MainWidget::TcpDisconnected()
{
    qDebug() << "Disconnected from server";
}

void MainWidget::TcpReadyRead()
{
    QByteArray data = m_TcpSocket->readAll();
    qDebug() << "Received data:" << data;
}

void MainWidget::TcpDisplayError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError);
    qDebug() << "Socket error:" << m_TcpSocket->errorString();
}

void MainWidget::UdpReadyRead()
{

}

void MainWidget::UdpDisplayError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError);
    qDebug() << "Socket error:" << m_UdpSocket->errorString();
}

void MainWidget::SaveData()
{
    if (!m_jsonDoc.isNull() && m_jsonDoc.isObject()) {
        QJsonObject jsonObj = m_jsonDoc.object();
        jsonObj["comm"] = ui->radioButtonTCP->isChecked()?"TCP":"UDP";
        jsonObj["ip"] = ui->lineEditIP->text();
        jsonObj["port"] = ui->lineEditPort->text();

        QJsonArray array;
        int irowCount = m_modelData->rowCount();
        for (int iRow = 0; iRow < irowCount; iRow++) {

            QJsonObject jsonData;
            jsonData["gid"] = m_modelData->item(iRow,0)->text();
            jsonData["gname"] = m_modelData->item(iRow,1)->text();
            if(m_modelData->item(iRow,2)->text() == "开机")
                jsonData["gturn"] = "true";
            else
                jsonData["gturn"] = "false";

            jsonData["gwallid"] = m_modelData->item(iRow,3)->text();
            jsonData["gadd"] = m_modelData->item(iRow,4)->text();
            array.push_back(jsonData) ;
        }

        jsonObj["data"] = array;
        //jsonObj.remove("data");
        //jsonObj.insert("data",array);
        m_jsonDoc.setObject(jsonObj);

        m_AppJson->saveJsonToFile(m_jsonDoc);
    }
}

void MainWidget::setCommEnabled(bool bComm)
{
    if(bComm)
    {
        ui->radioButtonTCP->setEnabled(false);
        ui->radioButtonUDP->setEnabled(false);
        ui->lineEditIP->setEnabled(false);
        ui->lineEditPort->setEnabled(false);
        ui->pushButtonLink->setText("关闭连接");
        ui->pushButtonLink->setStyleSheet("color: green;");
    }
    else
    {
        ui->radioButtonTCP->setEnabled(true);
        ui->radioButtonUDP->setEnabled(true);
        ui->lineEditIP->setEnabled(true);
        ui->lineEditPort->setEnabled(true);
        ui->pushButtonLink->setText("连接");
        ui->pushButtonLink->setStyleSheet("color: red;");
    }
}

void MainWidget::unConnect()
{
    if(ui->radioButtonTCP->isChecked())
    {
         m_TcpSocket->disconnectFromHost();
         if (m_TcpSocket->state() != QAbstractSocket::UnconnectedState) {
            m_TcpSocket->waitForDisconnected(3000);
         }
    }
    else
    {
         m_UdpSocket->close();
    }
    setCommEnabled(false);
    m_Comm = !m_Comm;
}

void MainWidget::onButtonRunClicked()
{
    if(!m_Comm)
    {
        QtHelper::showMessageBoxError("请先打开连接!");
         return;
    }

    QItemSelectionModel *selectionModel = ui->tableViewData->selectionModel();
    QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
    if (selectedIndexes.isEmpty())
    {
         QtHelper::showMessageBoxError("选择发送的行数据!");
         return;
    }

    QString serverIp = ui->lineEditIP->text();
    if(serverIp.isEmpty())
    {
         QtHelper::showMessageBoxError("请输入IP地址!");
         ui->lineEditIP->setFocus();
         return;
    }
    QHostAddress hostAddress(serverIp);

    QString sPort = ui->lineEditPort->text();
    if(sPort.isEmpty())
    {
         QtHelper::showMessageBoxError("请输入Port!");
         ui->lineEditPort->setFocus();
         return;
    }
    quint16 serverPort = sPort.toUShort();


    int currentRow = selectedIndexes.first().row();
    QStandardItem *item = NULL;

    item = m_modelData->item(currentRow, 1);
    QString strName = item->text();

    item = m_modelData->item(currentRow, 2);
    QString strPowerNum = item->text()=="开机"?"1":"0";
    QString strPower = item->text()=="开机"?"true":"false";
    QString strPowerText = item->text();

    item = m_modelData->item(currentRow, 3);
    QString strWallId = item->text();

    item = m_modelData->item(currentRow, 4);
    QString strAdd = item->text();

    QString strMsg = QString("您确定要执行【 %1 】\r\n【 %2 】操作吗？").arg(strName,strPowerText);

    if(QtHelper::showMessageBoxQuestion(strMsg) == QMessageBox::No)
        return;

    QString asciiData = QString("<AP,%1,%2,%3,%4>").arg(strPowerNum,strWallId,strPower,strAdd);
    QByteArray data = asciiData.toUtf8();

    if(ui->radioButtonTCP->isChecked()){
        //TCP
        if (m_TcpSocket->state() == QAbstractSocket::ConnectedState) {
            m_TcpSocket->write(data);
            m_TcpSocket->flush();
        }
    }
    else {
        // 发送数据
        qint64 bytesWritten = m_UdpSocket->writeDatagram(data, hostAddress, serverPort);
        if (bytesWritten == -1) {
            qDebug() << "Failed to send UDP datagram";
            QtHelper::showMessageBoxError("发送数据失败!");
            return;
        }
    }

    QtHelper::showMessageBox("发送数据操作成功!");
}

void MainWidget::onButtomNewClicked()
{
    stData* pData = new stData;
    pData->strName = "";
    pData->strWallid = "0";
    pData->strAddress = "";
    pData->bTurnOn = true;

    DialogAdd addDialog(pData);

    int result = addDialog.exec();  // 打开对话框
    if (result == QDialog::Accepted) {

        // 获取当前的系统日期和时间
        QDateTime currentDateTime = QDateTime::currentDateTime();

        QList<QStandardItem*> items;
        items << new QStandardItem(currentDateTime.toString("yyyyMMddhhmmss"))
              << new QStandardItem(pData->strName)
              << new QStandardItem(pData->bTurnOn?"开机":"关机")
              << new QStandardItem(pData->strWallid)
              << new QStandardItem(pData->strAddress);
        m_modelData->appendRow(items);

        SaveData();
        //qDebug() << "m_Name:" <<   addDialog.m_Name;

        // 处理对话框接受事件
    } else if (result == QDialog::Rejected) {

        //qDebug() << "Rejected:";
        // 处理对话框拒绝事件
    }

    delete pData;

    //ui->tableViewData->show();
}

void MainWidget::onButtomUpdateClicked()
{
    QItemSelectionModel *selectionModel = ui->tableViewData->selectionModel();
    QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
    if (selectedIndexes.isEmpty())
    {
        QtHelper::showMessageBoxError("选择修改的行数据!");
        return;
    }

    int currentRow = selectedIndexes.first().row();

    QStandardItem *item = NULL;
    stData* pData = new stData;
    item = m_modelData->item(currentRow, 1);
    pData->strName = item->text();
    item = m_modelData->item(currentRow, 2);
    pData->bTurnOn = item->text()=="开机"?true:false;
    item = m_modelData->item(currentRow, 3);
    pData->strWallid = item->text();
    item = m_modelData->item(currentRow, 4);
    pData->strAddress = item->text();

    DialogAdd addDialog(pData);

    int result = addDialog.exec();  // 打开对话框
    if (result == QDialog::Accepted) {

        // 获取当前的系统日期和时间
        item = m_modelData->item(currentRow, 1);
        item->setText(pData->strName);

        item = m_modelData->item(currentRow, 2);
        if(pData->bTurnOn)
            item->setText("开机");
        else
            item->setText("关机");

        item = m_modelData->item(currentRow, 3);
        item->setText(pData->strWallid);

        item = m_modelData->item(currentRow, 4);
        item->setText(pData->strAddress);

        SaveData();

        selectionModel->clearSelection();

        // 处理对话框接受事件
    } else if (result == QDialog::Rejected) {

        //qDebug() << "Rejected:";
        // 处理对话框拒绝事件
    }

    delete pData;
}

void MainWidget::onButtomDelClicked()
{
    QItemSelectionModel *selectionModel = ui->tableViewData->selectionModel();
    QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
    if (selectedIndexes.isEmpty())
    {
        QtHelper::showMessageBoxError("选择删除行!");
         return;
    }

    int currentRow = selectedIndexes.first().row();

    if(QtHelper::showMessageBoxQuestion("你确定要删除吗？") == QMessageBox::No)
        return;

    m_modelData->removeRow(currentRow);

    SaveData();

    selectionModel->clearSelection();
}

void MainWidget::onButtomLinkClicked()
{
    QString serverIp = ui->lineEditIP->text();
    if(serverIp.isEmpty())
    {
        QtHelper::showMessageBoxError("请输入IP地址!");
        ui->lineEditIP->setFocus();
        return;
    }
    QString sPort = ui->lineEditPort->text();
    if(sPort.isEmpty())
    {
        QtHelper::showMessageBoxError("请输入Port!");
        ui->lineEditPort->setFocus();
        return;
    }
    quint16 serverPort = sPort.toUShort();

    if(!m_Comm)//连接
    {
        if(ui->radioButtonTCP->isChecked())
        {
            if (m_TcpSocket->state() == QAbstractSocket::UnconnectedState)
                m_TcpSocket->connectToHost(serverIp, serverPort);

            if (!m_TcpSocket->waitForConnected(3000)) {
                QtHelper::showMessageBoxError("连接失败,请检查IP合端口!");
                return;
            }
        }
        else
        {
            if (!m_UdpSocket->bind()) {
                QtHelper::showMessageBoxError("连接失败,请检查IP合端口!");
                return ;
            }
        }
        setCommEnabled(true);
        m_Comm = !m_Comm;
    }
    else
    {

        unConnect();
//        if(ui->radioButtonTCP->isChecked())
//        {
//            //if (m_TcpSocket->state() == QAbstractSocket::ConnectedState)
//            //{
//            //    m_TcpSocket->disconnected();
//            //    m_TcpSocket.
//            //}

//            m_TcpSocket->disconnectFromHost();
//            if (m_TcpSocket->state() != QAbstractSocket::UnconnectedState) {
//                m_TcpSocket->waitForDisconnected(3000);
//            }
//        }
//        else
//        {
//            m_UdpSocket->close();
//        }
//        setCommEnabled(false);
//        m_Comm = !m_Comm;

    }
}

void MainWidget::onButtonRtLoginClicked()
{
    if (dialogLogin) {
        dialogLogin->emptyPwd();
        dialogLogin->show();
        hide();
        if(m_Comm)
        {
            this->unConnect();
        }
    }
}


